package com.xbn.netty.nettyHeartBeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author XBN
 * @date 2020/10/21 19:14
 * @email 78742541@qq.com
 */
/*
* 相应心跳监测事件
* */
public class MyServerHeartHandler extends ChannelInboundHandlerAdapter {
    /*
    * @param ctx上下文
    * @param evt事件
    * */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent)
        {
            //evt向下转型
            IdleStateEvent event= (IdleStateEvent) evt;
            String eventType=null;
            switch (event.state())
            {
                case READER_IDLE:
                    eventType="读空闲";
                    break;
                case WRITER_IDLE:
                    eventType="写空闲";
                    break;
                case ALL_IDLE:
                    eventType="读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress()+"长时间未"+eventType+"，超时,服务器关闭此连接");
            //如果触发任何读写空间，我们都去关闭通道连接
            ctx.channel().close();
        }
    }
}
